package br.com.emmis.tercons.controller;

import android.os.Handler;
import android.os.Message;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import br.com.emmis.tercons.model.TercoModel;
import br.com.emmis.tercons.model.interfaces.Pray;

/**
 * Created by vaner on 03/10/2014.
 */
public class TercoStateMachine {

    private List<TercoStateMachineListener> mListeners;
    private Timer mTimer;
    private TercoModel mTerco;
    private int mPrayIndex;
    public Handler mHandler;
    public boolean mIgnoreTimer;

    private boolean mAutomatic;
    private int mNumberOfPrays;

    public TercoStateMachine(){
        mListeners = new ArrayList<TercoStateMachineListener>();
        mTerco = new TercoModel();
        mPrayIndex = 0;
        mAutomatic = true;
        mNumberOfPrays = mTerco.getListOfPrays().size();

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                nextPray();
            }
        };
    }

    public void addTercoStateMachineListener(TercoStateMachineListener listener) {
        mListeners.add(listener);
    }

    public void startTerco() {
        nextPray();
    }

    public void nextPray() {
        mIgnoreTimer = true;

        if(mPrayIndex >= mNumberOfPrays) {
            for(TercoStateMachineListener listener : mListeners) {
                listener.OnPrayFinished();
                return;
            }
        }

        Pray pray = mTerco.getListOfPrays().get(mPrayIndex);

        if(mAutomatic) {
            mTimer = new Timer();
            mTimer.schedule(new PrayTask(), pray.averageTime() * 1000);
            mIgnoreTimer = false;
        }

        for(TercoStateMachineListener listener : mListeners) {
            listener.OnPrayChanged(pray);
        }
        mPrayIndex++;
    }

    public boolean ismAutomatic() {
        return mAutomatic;
    }

    public void setmAutomatic(boolean mAutomatic) {
        this.mAutomatic = mAutomatic;
    }

    public void stopTerco() {
        mIgnoreTimer = true;
    }

    class PrayTask extends TimerTask {
        public void run() {
            if(!mIgnoreTimer) {
                mHandler.sendMessage(Message.obtain());
                mTimer.cancel();
            }
        }
    }
}
